#include "TGObject.h"
#include "World.h"

namespace TG
{
	TGObject::TGObject():enable(true)
	{
	}

	TGObject::~TGObject()
	{
	}

	TGObject* TGObject::instantiate(const char* name)
	{
		auto go = new TGObject();
		go->name = name;
		return go;
	}

	void TGObject::destroy(TGObject *go)
	{
		if (go->parent != NULL)
		{
			go->parent->childs.remove(go);
			go->parent = NULL;
		}

		for (auto it = go->childs.begin(); it != go->childs.end(); ++it)
		{
			destroy(*it);
			delete *it;
		}

		for (auto it = go->components.begin(); it != go->components.end(); ++it)
		{
			if ((*it)->life < LIFT::DISABLE && (*it)->life >= LIFT::ENABLE)
			{
				(*it)->onDisable();
			}
			(*it)->onDestroy();
			delete (*it);
		}

		delete go;
	}

	void TGObject::setEnable(bool b)
	{
		enable = b;

		if (b)
		{
			for (auto it = components.begin(); it != components.end(); ++it)
			{
				(*it)->onEnable();
			}
		}
		else 
		{
			for (auto it = components.begin(); it != components.end(); ++it)
			{
				(*it)->onDisable();
			}
		}
	}

	mat4x4 TGObject::getMatrix()
	{
		mat4x4 mat = translate(position.x, position.y, position.z);
		mat = rotateX(rotation.x) * mat;
		mat = rotateY(rotation.y) * mat;
		mat = rotateZ(rotation.z) * mat;
		//mat = TG::scale(scale.x, scale.y, scale.z) * mat;
		//mat4x4 mat;
		//mat.identify();
		return mat;
	}

	void TGObject::addChild(TGObject* go)
	{
		childs.push_back(go);
	}

	void TGObject::setParent(TGObject* parent)
	{
		this->parent = parent;
		if (parent != NULL)
		{
			parent->addChild(this);
		}
	}
}